package com.sjgl.esdn.utils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;

import java.io.*;


/**
 * @author CSF
 */
public class TextUtilESDN {

    public static String[] TEXT_FILE_EXTD = new String[] {"txt", "doc", "docx","pdf","ppt","pptx","xls","xlsx"};


    /**
     * 判断是否合法
     * @param ext
     * @return
     */
    public static boolean isFileAllowed(String ext) {
        for (String format:TEXT_FILE_EXTD) {
            if (ext.toLowerCase().equals(format)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 用来读取txt文件的方法
     * @param filePath
     * @return
     */
    public static String getTextFromTxt(String filePath){
        String encoding = EncodingDetectESDN.getJavaEncode(filePath);
        File file = new File(filePath);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 用来读取doc文件的方法
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String getTextFromDoc(String filePath) throws Exception{

        FileInputStream fis = new FileInputStream(new File(filePath));
        WordExtractor extractor = new WordExtractor(fis);

        return extractor.getText();

    }

    /**
     * 用来读取docx文件
     * @param filePath
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String getTextFromDocx(String filePath) throws IOException {
        FileInputStream in = new FileInputStream(filePath);
        XWPFDocument doc = new XWPFDocument(in);
        XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
        String text = extractor.getText();
        in.close();
        return text;
    }

    /**
     * 用来读取pdf文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String getTextFromPDF(String filePath) throws IOException{
        File input = new File(filePath);
        PDDocument pd = PDDocument.load(input);
        PDFTextStripper stripper = new PDFTextStripper();
        String res = stripper.getText(pd);
        pd.close();
        return res;
    }

    /**
     * 用来读取ppt文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String getTextFromPPT( String filePath) throws IOException{
        FileInputStream in = new FileInputStream(filePath);
        PowerPointExtractor extractor = new PowerPointExtractor(in);
        String content = extractor.getText();
        extractor.close();
        return content;
    }

    /**
     * 用来读取pptx文件
     * @param filePath
     * @return
     * @throws IOException
     * @throws XmlException
     * @throws OpenXML4JException
     */
    public static String getTextFromPPTX(String filePath) throws IOException, XmlException, OpenXML4JException {
        File ppt = new File(filePath);
        OPCPackage pkg = OPCPackage.open(ppt);
        XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(pkg);
        String content = extractor.getText();
        extractor.close();
        return content;
    }
    /**
     * 用来读取xls文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String getTextFromXLS(String filePath) throws IOException {
        FileInputStream in = new FileInputStream(filePath);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(in);
        StringBuilder sb = new StringBuilder();
        for(int numSheet=0;numSheet<hssfWorkbook.getNumberOfSheets();numSheet++){
            HSSFSheet hssfSheet=hssfWorkbook.getSheetAt(numSheet);
            if(hssfSheet==null){
                continue;
            }
            for(int rowNum=1;rowNum<hssfSheet.getLastRowNum();rowNum++){
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                int firstCellNum = hssfRow.getFirstCellNum();
                int lastCellNum = hssfRow.getLastCellNum();
                for(int cellNum=firstCellNum;cellNum<lastCellNum;cellNum++){
                    HSSFCell cell = hssfRow.getCell(cellNum);
                    if(cell==null){
                        continue;
                    }
                    sb.append(cell);
                }
            }
        }
        return sb.toString();
    }
    /**
     * 用来读取xls文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String getTextFromXLSX(String filePath) throws Exception {
        InputStream in = new FileInputStream(filePath);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
        StringBuilder sb = new StringBuilder();
        //循环每一页，并处理当前的循环页
        for (Sheet sheet : xssfWorkbook) {
            if (sheet == null) {
                continue;
            }
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);//Row表示每一行的数据
                int minColIx = row.getFirstCellNum();
                int maxColIx = row.getLastCellNum();
                //遍历该行，并获取每一个cell的数据
                for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                    Cell cell = row.getCell(colIx);
                    if (cell == null) {
                        continue;
                    }
                    sb.append(cell);
                }
            }
        }
        return sb.toString();
    }

}
